package io.wdb.wx.service.impl;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.springframework.stereotype.Service;

import io.wdb.common.exception.RRException;
import io.wdb.common.utils.DateFormatUtil;
import io.wdb.modules.activity.wx.dao.MarketIntegralInfoDao;
import io.wdb.modules.activity.wx.dao.MarketPrizeDao;
import io.wdb.modules.activity.wx.dao.MarketUserPrizeDao;
import io.wdb.modules.activity.wx.dao.MarketUserRankDao;
import io.wdb.modules.activity.wx.dao.MarketUserSubscribeDao;
import io.wdb.modules.activity.wx.dao.UserChannelInfoDao;
import io.wdb.modules.activity.wx.entity.MarketIntegralInfoEntity;
import io.wdb.modules.activity.wx.entity.MarketPrizeEntity;
import io.wdb.modules.activity.wx.entity.MarketUserPrizeEntity;
import io.wdb.modules.activity.wx.entity.MarketUserRankEntity;
import io.wdb.modules.activity.wx.entity.MarketUserSubscribeEntity;
import io.wdb.modules.activity.wx.entity.UserChannelInfoEntity;
import io.wdb.wx.message.resp.prize.PrizeNumVO;
import io.wdb.wx.service.PrizeService;

@Service("prizeServiceImpl")
public class PrizeServiceImpl implements PrizeService{
	@Resource(name="marketUserRankDao")
	private MarketUserRankDao marketUserRankDao;
	
	@Resource(name="userChannelInfoDao")
	private UserChannelInfoDao userChannelInfoDao;
	
	@Resource(name="marketUserPrizeDao")
	private MarketUserPrizeDao marketUserPrizeDao;
	
	@Resource(name="marketUserSubscribeDao")
	private MarketUserSubscribeDao marketUserSubscribeDao;
	
	@Resource(name="marketPrizeDao")
	private MarketPrizeDao marketPrizeDao;
	
	@Resource(name="marketIntegralInfoDao")
	private MarketIntegralInfoDao marketIntegralInfoDao;
	@Override
	public PrizeNumVO getUserIntegral(Long userId) throws RRException {
		PrizeNumVO prizeNumVO = new PrizeNumVO();
		MarketUserRankEntity entity = marketUserRankDao.getUserIntegral(userId);
		Long userCurrentIntegral = entity.getUserIntegralAvailable();
		Long num = userCurrentIntegral/100l;
		prizeNumVO.setUser_integral(userCurrentIntegral);
		prizeNumVO.setUser_prize_num(num);
		return prizeNumVO;
	}

	@Override
	public UserChannelInfoEntity getUserInfo(Long userId) throws RRException {
		return userChannelInfoDao.getUserInfo(userId);
	}

	@Override
	public void submietUserPrize(UserChannelInfoEntity userChannelInfoEntity, MarketPrizeEntity marketPrizeEntity)
			throws RRException {
		//1：用户抽奖情况入库
		MarketUserPrizeEntity marketUserPrizeEntity = new MarketUserPrizeEntity();
		marketUserPrizeEntity.setCreateTime(new Date());
		marketUserPrizeEntity.setPrizeId(marketPrizeEntity.getId());
		marketUserPrizeEntity.setPrizeName(marketPrizeEntity.getPrizeName()+marketPrizeEntity.getPrizeNamePart());
		marketUserPrizeEntity.setUserId(userChannelInfoEntity.getId());
		marketUserPrizeDao.insert(marketUserPrizeEntity);
		//2：用户积分流水入库
		MarketIntegralInfoEntity marketIntegralInfoEntity = new MarketIntegralInfoEntity();
		marketIntegralInfoEntity.setChangeType(1);
		marketIntegralInfoEntity.setCreateTime(new Date());
		marketIntegralInfoEntity.setIntegralChange(-100);
		marketIntegralInfoEntity.setUserId(userChannelInfoEntity.getId());
		marketIntegralInfoDao.insert(marketIntegralInfoEntity);
		//3：用户可用积分变更
		MarketUserRankEntity marketUserRankEntity = marketUserRankDao.getUserIntegral(userChannelInfoEntity.getId());
		Long userCurrentIntegral = marketUserRankEntity.getUserIntegralAvailable();
		if(null!=marketPrizeEntity.getPrizeType()&&marketPrizeEntity.getPrizeType()==0) {
			String prizeNamePart = marketPrizeEntity.getPrizeNamePart();
			Integer index = prizeNamePart.lastIndexOf("0");
			Long addIntegral = Long.valueOf(prizeNamePart.substring(0,index+1));
			userCurrentIntegral = userCurrentIntegral+addIntegral;
		}
		marketUserRankEntity.setUserIntegralAvailable(userCurrentIntegral-100l);
		marketUserRankDao.update(marketUserRankEntity);
		//4: 奖品剩余数量变更 TODO
		// 暂时不修改奖品剩余数量
		marketPrizeEntity.setPrizeNumResidue(marketPrizeEntity.getPrizeNumResidue()-1);
		marketPrizeDao.update(marketPrizeEntity);
	}
	@Override
	public List<MarketPrizeEntity> getAllPrizes() {
		return marketPrizeDao.getAllPrizes();
	}

	@Override
	public UserChannelInfoEntity initUserInfo(String openId, String headImgUrl, String nickname) {
		UserChannelInfoEntity channelInfo = new UserChannelInfoEntity();
		Date now = new Date();
		channelInfo.setAccountId(openId);
		channelInfo.setAccountType(1);
		channelInfo.setChannelImg(headImgUrl);
		channelInfo.setChannelNickName(nickname);
		channelInfo.setCreateTime(now);
		channelInfo.setStatus(0);
		channelInfo.setUserInfoId(null);
		channelInfo.setSex("1");
		channelInfo.setCity("上海");
		channelInfo.setReissueCard(0);
		//新增订阅用户
		userChannelInfoDao.save(channelInfo);
		//新增用户订阅累计表
		MarketUserSubscribeEntity marketUserSubscribe = new MarketUserSubscribeEntity();
		marketUserSubscribe.setBorrowCount(0);
		marketUserSubscribe.setCreateTime(now);
		marketUserSubscribe.setRepayCount(0);
		marketUserSubscribe.setResidueCount(0);
		marketUserSubscribe.setSubscribeCount(0);
		marketUserSubscribe.setBorrowCount(0);
		marketUserSubscribe.setUserId(channelInfo.getId());
		marketUserSubscribeDao.save(marketUserSubscribe);
		
		MarketUserRankEntity marketUserRank = new MarketUserRankEntity();
		marketUserRank.setCreateTime(now);
		marketUserRank.setUserId(channelInfo.getId());
		marketUserRank.setUserIntegral(80l);
		marketUserRank.setUserPraiseCount(0);
		marketUserRank.setUserSignCount(0);
		marketUserRank.setUserSingContentCount(0);
		marketUserRank.setUserIntegralAvailable(80l);
		marketUserRankDao.save(marketUserRank);
		return channelInfo;
	}

	@Override
	public void updateUserInfo(UserChannelInfoEntity channelInfo) {
		userChannelInfoDao.update(channelInfo);
	}

	@Override
	public String export(List<? extends Object> list, String fileName) {
		HSSFWorkbook workbook = new HSSFWorkbook();
		HSSFSheet sheet = workbook.createSheet("one");
		int rowNum = 0;
		for(Object obj:list) {
			try {
				this.writeObj(obj, sheet, rowNum);
			} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
				e.printStackTrace();
			}
			rowNum++;
		}
		FileOutputStream fos= null;
		try {
			fos = new FileOutputStream("export-prize"+DateFormatUtil.formatDate(new Date())+".xls");
			workbook.write(fos);
			fos.flush();
			return "export-prize"+DateFormatUtil.formatDate(new Date())+".xls";
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if(fos!=null) {
					fos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	private void  writeObj(Object obj,HSSFSheet sheet,int rowNum) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		HSSFRow rowHead = null;
		HSSFRow row = null;
		if(rowNum==0) {
			rowHead = sheet.createRow(rowNum);
		}
		row = sheet.createRow(rowNum+1);
		Method[] methods = obj.getClass().getDeclaredMethods();
		int i = 0;
		String returnValue = null;
		for(Method method:methods) {
			String methodName = method.getName();
			if(methodName.startsWith("get")) {
				Object returnObj = method.invoke(obj, null);
				if(returnObj!=null) {
					if(rowNum==0) {
						Cell cellHead = rowHead.createCell(i);
						cellHead.setCellValue(methodName.replaceAll("get", ""));
					}
					if(returnObj.getClass().equals(Date.class)) {
						returnValue = DateFormatUtil.formatDateTime((Date)returnObj);
					}else {
						returnValue = returnObj.toString();
					}
					Cell cell = row.createCell(i);
					cell.setCellValue(returnValue);
					i++;
				}
			}
		}
	}
}
